package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /*
     * 员工登录
     * 1.将员工输入的密码转成md5加密后的密码
     * 2.在数据库中查找该员工是否存在
     * 3.员工存在了是否密码正确
     * 4.员工是否被禁用
     * */
    @PostMapping("login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("员工:{},正在登录...", employee.getUsername());
        String pwd = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes(StandardCharsets.UTF_8));

        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Employee::getUsername, employee.getUsername());

        Employee emp = employeeService.getOne(lambdaQueryWrapper);

        if (emp == null) {
            log.info("员工:{},登录失败...无该用户", employee.getUsername());
            return R.error("登陆失败---无该用户");
        }

        if (emp.getPassword().equals(pwd) == false) {
            log.info("员工:{},登录失败...密码错误", employee.getUsername());
            return R.error("登陆失败---密码错误");
        }


        if (emp.getStatus() == Employee.EmployeeStatus.NotIsNumber.getStatus()) {
            log.info("员工:{},登录失败...已被禁用", employee.getUsername());
            return R.error("登陆失败---已被禁用");
        }
        log.info("员工:{},登录成功...", employee.getUsername());
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        log.info("员工id:{},推出成功...", request.getSession().getAttribute("employee"));
        //清理session中保存的当前登录员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 员工信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R<Page> list(int page, int pageSize, String name) {
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //执行查询
        employeeService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 员工退出
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        log.info("新增员工，员工信息：{}", employee.toString());

        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        employeeService.save(employee);

        return R.success("新增员工成功");
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<Employee> getInfo(@PathVariable Long id) {
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if (employee == null) {
            return R.error("无该员工信息");
        } else {
            return R.success(employee);
        }
    }
    /**
     * 更新员工信息
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> modifyEmployee(@RequestBody Employee employee) {
        log.info("更新员工：{}信息...",employee.toString());
        employeeService.updateById(employee);
        return R.success("修改成功");
    }
}
